<div id="formDiv"></div>
<script type="text/html" id="warehouseProductionOrderformContent">
  <form lay-filter="warehouseProductionOrderForm" id="warehouseProductionOrderForm" class="layui-form open-form">
    <div class="open-model">
      <div class="open-auto">
        <div>
          <div class="layui-form-item layui-row">
            <input name="id" type="hidden" />
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">选择客户</label>

              <div class="layui-input-block">
                <select id="customerId" name="customerId" lay-filter="customerId"  lay-search required></select>
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label"> 所属生产订单</label>
              <input  name="productionOrderNumber" type="hidden" />
              <div class="layui-input-block">
                <select id="productionOrderId" name="productionOrderId" lay-filter="productionOrderId"  lay-search required></select>
              </div>
            </div>

            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label"> 产线</label>
              <input  name="productionOrderNumber" type="hidden" />
              <div class="layui-input-block">
                <select id="productionLineId" name="productionLineId" lay-filter="productionLineId"  lay-search required></select>
              </div>
            </div>
          
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">计划交货时间</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input" id="deliveryTime" name="deliveryTime" disabled />
              </div>
            </div>


          </div>
          <div class="layui-form-item layui-row">
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">品种</label>
              <input  name="productVarietyId" type="hidden" />
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="productVarietyName" disabled name="productVarietyName" />
              </div>
            </div>
<!--            <div class="layui-inline layui-col-md3">-->
<!--              <label class="layui-form-label">	规格</label>-->
<!--              <div class="layui-input-block">-->
<!--                <input class="layui-input adv-disable" id="productSpecCode" disabled name="productSpecCode" />-->
<!--              </div>-->
<!--            </div>-->
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">牌号</label>
              <input  name="productMarkId" type="hidden" />
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="productMarkName" disabled name="productMarkName" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">生产商</label>
              <input  name="productProducerId" type="hidden" />
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="productProducerName" disabled name="productProducerName" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">剩余排产数量</label>
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="remainingProductionSchedule" disabled name="remainingProductionSchedule" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">加工类型</label>
              <div class="layui-input-block">
                <input  name="processingType" type="hidden" />
                <input class="layui-input adv-disable" id="processingTypeName" disabled name="processingTypeName" />
              </div>
            </div>
          </div>
<!--          <div class="layui-form-item layui-row">-->
<!--            <div class="layui-inline layui-col-md3">-->
<!--              <label class="layui-form-label">厚度/壁厚/直径</label>-->
<!--              <div class="layui-input-block">-->
<!--                <input type="text" class="layui-input " id="diameter" disabled name="diameter" />-->
<!--              </div>-->
<!--            </div>-->
<!--            <div class="layui-inline layui-col-md3">-->
<!--              <label class="layui-form-label">宽度/外径</label>-->
<!--              <div class="layui-input-block">-->
<!--                <input type="text" class="layui-input" id="width" disabled name="width" />-->
<!--              </div>-->
<!--            </div> <div class="layui-inline layui-col-md3">-->
<!--              <label class="layui-form-label">长度</label>-->
<!--              <div class="layui-input-block">-->
<!--                <input type="text" class="layui-input" id="length" disabled name="length" />-->
<!--              </div>-->
<!--            </div>-->
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">备注</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input" id="remark" name="remark" />
              </div>
            </div>

          </div>
<!--          <div class="layui-form-item layui-row">-->
<!--            <div class="layui-inline layui-col-md3">-->
<!--              <label class="layui-form-label">图纸</label>-->
<!--              <div class="layui-input-block">-->
<!--                <input type="hidden" class="layui-input adv-disable" id="processingDrawing" disabled name="processingDrawing" />-->
<!--                <button class="layui-btn layui-btn-sm" id="processingDrawingBtn" type="button">-->
<!--                  查看附件-->
<!--                </button>-->
<!--              </div>-->
<!--            </div>-->
<!--            <div class="layui-inline layui-col-md3">-->
<!--              <label class="layui-form-label">材料料号</label>-->
<!--              <div class="layui-input-block">-->
<!--                <button class="layui-btn layui-btn-sm" id="materialDetail" type="button">无物料</button>-->
<!--                <input  class="layui-input" type="hidden" id="materialNumber" name="materialNumber" />-->
<!--              </div>-->
<!--            </div>-->
            <div class="layui-inline layui-col-md3">
<!--              <label class="layui-form-label">材料料号</label>-->
              <div class="layui-input-block">
<!--                <button class="layui-btn layui-btn-sm" id="sysBundleListDetail" type="button">无物料</button>-->
                <input  class="layui-input" type="hidden" id="sysBundleList" name="sysBundleList" />
              </div>
            </div>
            <!-- <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">计划生产数量</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input" disabled name="plannedQuantity" />
              </div>
            </div> -->


           </div>
        <div class="layui-form-item tableContent">
          <!-- {{# if(d.eventName !== 'detail'){ }} -->
          <!-- <button class="layui-btn" type="button" id="Configure">添加排产信息</button> -->
          <!-- {{# } }} -->
          <table class="layui-table" id="purchasePlanFormTable" lay-filter="purchasePlanFormTable"></table>
        </div>

        <div class="layui-form-item text-right">
          <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
          <button class="layui-btn" lay-filter="formSubmit" type="button" lay-submit>提交</button>
        </div>
      </div>
    </div>
  </form>
</script>

<script type="text/html" id="purchasePlanFormTableBar">
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="customerSku">
  <div class="open-form">
    <div class="open-model">
      <div class="open-auto">
        <button class="layui-btn " id="addCustomerSku">确认选择</button>
        <table class="layui-table" id="customerSkuTable"></table>
      </div>
    </div>
  </div>
</script>
<script type="text/html" id="warehouseMaterialRequisitionRecordForm">
  <div class="open-form">
    <div class="open-model">
      <div class="open-auto">
        <table class="layui-table" id="warehouseMaterialRequisitionRecordTable" lay-filter="warehouseMaterialRequisitionRecordTable"></table>
      </div>
    </div>
  </div>
</script>
<script>
  layui.use(["layer", "form", "table", "admin", "laydate", "upload", "laytpl"], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    let laydate = layui.laydate;
    let laytpl = layui.laytpl;
    const nowData = { ...parentData };
    let data = nowData?.data;
    let skuList = [];

    laytpl(warehouseProductionOrderformContent.innerHTML).render({ ...nowData }, function (html) {
      $("#formDiv").after(html);
    });
    // 初始化日期选择
    laydate.render({
      elem: "#deliveryTime",
      type: "datetime"
    });

    await admin.initDataSelectPro(
      "warehouse/warehouse/productionLine/list",
      {

      },
      "productionLineId",
      "产线",
      async (d, obj) => {
        form.render(); // 重新渲染表单
      },
      "productionLineName"
    );

    // 初始化客户选择
    await admin.initDataSelectPro(
      "enterprise/sell/admin/customersInfo/list",
      { limit: 99999 },
      "customerId",
      "客户名称",
      async (d) => {
        $("#contractId").empty();
        $("#contractId").val("");
        $("#productionOrderId").empty();
        $("#productionOrderId").val("");
        if (d.value) {
          await admin.initDataSelectPro(
            "warehouse/warehouse/productionOrder/list",
            {
              customerId: d.value,
              status: 2
            },
            "productionOrderId",
            "生产订单编号",
            async (d, obj) => {
              // form.val("warehouseProductionOrderForm", {
              //   productVarietyId: "",
              //   productSpecCode: "",
              //   requiredQuantity: "",
              //   diameter: "",
              //   width: "",
              //   length: "",
              //   materialNumber: "",
              //   sysBundleList: "",
              //   processingDrawing: "",
              //   productVarietyName: "",
              //   productMarkName: "",
              //   productMarkId:"",
              //   productProducerId:"",
              //   productVarietyId: "",
              //   productProducerName: "",
              //   processingTypeName: "",
              //   processingType: "",
              //   remark: "",
              //   productionOrderNumber: "",
              //   productId: ""
              // });
              if (d.value) {

                // obj.id ? delete obj.id : "";
                console.log(obj);
               
                let res = await admin.reqPro("warehouse/warehouse/productionOrder/selectProductionDetail", { id: obj.id });
                form.val("warehouseProductionOrderForm", res.data);
                console.log(res.data.warehouseProductionOrderDetailList);
                res.data.warehouseProductionOrderDetailList.map(v => {
                  v.productionOrderDetailId = v.id;
                });
                table.reload("purchasePlanFormTable", {
                  data: res.data.warehouseProductionOrderDetailList,
                });
                form.render(); // 重新渲染表单
              } else {
                table.reload("purchasePlanFormTable", {
                  data: [],
                });
              }
            },
            "productionOrderNumber"
          );
        }
      },
      "customerName"
    );
    const workshopData = await admin.reqPro("enterprise/device/admin/deviceWorkshop/list", {});
    const workshopList = workshopData.data.map((v) => {
      return {
        label: v.name,
        value: v.id
      };
    });
    const productionLineData = await admin.reqPro("warehouse/warehouse/productionLine/list", {});
    const productionLineList = productionLineData.data.map((v) => {
      return {
        label: v.workshopName,
        value: v.id,
        workshopId: v.workshopId
      };
    });
    if (nowData.eventName === "detail") {
      admin.setFormDisable("#warehouseProductionOrderForm", true);
    }

    const tableVal = table.render({
      elem: "#purchasePlanFormTable",
      page: false,
      limit: 999999,
      height: 400,
      data: [],
      cols: [
        [
          { type: "numbers", title: "序号", width: 80 },
          {
            field: 'productSpecCode', title: '规格', width: 120, templet: function (d) {
              return d.productSpecCode !== null && d.productSpecCode !== undefined && d.productSpecCode !== "" ? d.productSpecCode : '无';
            }
          },
          {
            field: 'diameter', title: '厚度/壁厚/直径', width: 150, templet: function (d) {
              return d.diameter !== null && d.diameter !== undefined && d.diameter !== "" ? d.diameter : '无';
            }
          },
          {
            field: 'warehouseWidth', title: '宽度/外径', width: 120, templet: function (d) {
              return d.warehouseWidth !== null && d.warehouseWidth !== undefined && d.warehouseWidth !== "" ? d.warehouseWidth : '无';
            }
          },
          {
            field: 'warehouseLength', title: '长度', width: 100, templet: function (d) {
              return d.warehouseLength !== null && d.warehouseLength !== undefined && d.warehouseLength !== "" ? d.warehouseLength : '无';
            }
          },
          {
            field: 'bundleQuantity', title: '捆包件数', width: 100, templet: function (d) {
              return d.bundleQuantity !== null && d.bundleQuantity !== undefined && d.bundleQuantity !== "" ? d.bundleQuantity : '无';
            }
          }, {
            field: 'requiredQuantity', title: '需求数', width: 100, templet: function (d) {
              return d.requiredQuantity !== null && d.requiredQuantity !== undefined && d.requiredQuantity !== "" ? d.requiredQuantity : '无';
            }, hide: nowData.eventName === "detail",
          },
          {
            field: 'plannedQuantity', title: '计划生产数量', width: 120,
            templet: function (d) {
              return admin.setTableInput("plannedQuantity", nowData.eventName == "detail", "plannedQuantity")(d);
            }
          },
          {
            field: 'bundleSum',
            title: '捆包数量',
            width: 120,
            templet: function (d) {
              // 如果 plannedQuantity 或 bundleQuantity 为 0，则显示 0
              if (!d.plannedQuantity || !d.bundleQuantity) {
                return '0';
              }
              // 否则计算捆包数量：计划数 / 捆包件数（取整）
              const bundleSum = Math.ceil(d.plannedQuantity / d.bundleQuantity);
              return bundleSum || '0';
            }
          },
          {
            field: 'materialNumber', title: '材料料号', width: 120, templet: function (d) {
              return d.materialNumber !== null && d.materialNumber !== undefined && d.materialNumber !== "" ? d.materialNumber : '无';
            }
          }, {
            field: 'scheduleQuantity', title: '剩余排产数', width: 120, templet: function (d) {
              return d.scheduleQuantity !== null && d.scheduleQuantity !== undefined && d.scheduleQuantity !== "" ? d.scheduleQuantity : '无';
            },hide: nowData.eventName === "detail",
          },
          {
            field: 'remark',
            title: '备注',
            width: 120,
            templet: function (d) {
              return admin.setTableInput("remark", nowData.eventName == "detail", "remark")(d);
            }
          }, {
            align: "center",
            toolbar: "#purchasePlanFormTableBar",
            title: "操作",
            width: 100,
            hide: nowData.eventName === "detail"
          }
        ]
      ],
      done: function (tableData) {
        const fields = ["remark", "plannedQuantity", "bundleQuantity"];
        let debounceTimer; // Moved to outer scope
        fields.forEach(function (field) {
          admin.tableInputChangeByClass("purchasePlanFormTable", field, function (index, value, tableData, field, tableId) {
            let rowIndex = tableData.findIndex((v) => v["LAY_TABLE_INDEX"] == index);
            if (rowIndex > -1) {
              if (field === "plannedQuantity" || field === "bundleQuantity") {
                console.log(1111,"jiasjais")
                tableData[rowIndex][field] = parseInt(value) || 0;

                const plannedQuantity = tableData[rowIndex].plannedQuantity || 0;
                const bundleQuantity = tableData[rowIndex].bundleQuantity || 0;
                const bundleSum = bundleQuantity ? Math.floor(plannedQuantity / bundleQuantity) : 0;
                console.log(bundleSum,"bundleSum")
                tableData[rowIndex].bundleSum = bundleSum;

                clearTimeout(debounceTimer);
                debounceTimer = setTimeout(() => {
                  table.reload(tableId, {
                    data: tableData.data,
                    where: { LAY_TABLE_INDEX: index }
                  });
                }, 500);
              } else {
                tableData[rowIndex][field] = value;
              }
            }
          });
        });

        tableData.data.forEach((v) => {
          laydate.render({
            elem: ".plannedProductionTime" + v.LAY_TABLE_INDEX,
            type: "datetime",
            done: function (value, date, endDate) {
              v.plannedProductionTime = value;
            }
          });
        });
      }
    });

    // Add table event handler
    table.on('tool(purchasePlanFormTable)', function (obj) {
      var data = obj.data;
      if (obj.event === 'del') {
        layer.confirm('确定要删除该行数据吗？', function (index) {
          obj.del();
          layer.close(index);
        });
      }
    });

    if (data && data.id) {
      await admin.initDataSelectPro(
        "warehouse/warehouse/productionOrder/list",
        {
          customerId: data.customerId
        },
        "productionOrderId",
        "生产订单编号",
        async (d, obj) => {


          if (d.value) {
            delete obj.id;
            form.val("warehouseProductionOrderForm", { productionOrderNumber: obj.productionOrderNumber });

            const { data } = await admin.reqPro("warehouse/warehouse/productionOrder/selectProductionDetail", { id: d.value });


          }
        },
        "productionOrderNumber"
      );
      const res = await admin.reqPro("warehouse/warehouse/productionOrder/selectProductionDetail", { id: data.productionOrderId });

      form.val("warehouseProductionOrderForm", data);
      $("#materialDetail").text(data.materialNumber ? data.materialNumber : "无物料");
      // 生产计划详情和制造令详情公用一个  区别有无productId

      console.log(data);

      tableVal.reload({
        data: data.warehouseProductionSchedulingPlanDetailList
      });
    } else {
      // tableVal.reload({
      //   data: [
      //     {
      //       workshopId: "",
      //       productionLineId: "",
      //       plannedProductionTime: "",
      //       plannedQuantity: "",
      //       remark: ""
      //     }
      //   ]
      // });
    }

    form.on("submit(formSubmit)", function (d) {
      let formData = { ...d.field };
      // 需求数要求数字类型
      formData.requiredQuantity = Number(formData.requiredQuantity);
      formData.scheduleQuantity = Number(formData.scheduleQuantity);
      formData.remainingProductionSchedule = Number(formData.remainingProductionSchedule);
      formData.productionOrderDetailId = Number(formData.productionOrderDetailId);
      formData.warehouseProductionSchedulingPlanDetailListVO = table.cache["purchasePlanFormTable"].map((v) => {
        v.plannedQuantity = Number(v.plannedQuantity);
        v.workshopName = workshopList.find((v1) => v1.value == v.workshopId)?.label; // 车间名称
        v.productionLineName = productionLineList.find((v1) => v1.value == v.productionLineId)?.label; // 产线名称
        return v;
      });
      if (formData.warehouseProductionSchedulingPlanDetailListVO.some((v) => v.workshopId == "" && v.productionLineId == "")) {
        layer.msg("请完善表格数据");
        return false;
      }
      if (formData.warehouseProductionSchedulingPlanDetailListVO.length == 0) {
        layer.msg("请添加排产信息");
        return false;
      }
      formData.plannedQuantity = formData.warehouseProductionSchedulingPlanDetailListVO.reduce((v, c) => v + Number(c.plannedQuantity), 0);
      if (formData.plannedQuantity > formData.scheduleQuantity) {
        // 弹框确认是否继续
        layer.confirm("计划生产数量大于需求数，是否继续", { icon: 3, title: "提示" }, function (index) {
          submitForm(formData);
        });
      } else {
        submitForm(formData);
      }

      return false;
    });
    function submitForm(formData) {
      if (nowData.eventName == "add") {
        delete formData.id;
        admin.req(
          "warehouse/warehouse/productionSchedulingPlan/add",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("ProductionOrderTable");
              layer.closeAll("page");
            } else {
              layer.msg(res.msg, { icon: 2, time: 1000 });
            }
          },
          "POST",
          false,
          "application/json"
        );
      } else if (nowData.eventName == "edit") {
        admin.req(
          "warehouse/warehouse/productionSchedulingPlan/update",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("ProductionOrderTable");
              layer.closeAll("page");
            } else {
              layer.msg(res.msg, { icon: 2, time: 1000 });
            }
          },
          "POST",
          false,
          "application/json"
        );
      }
    }
    table.on("tool(purchasePlanFormTable)", function (obj) {
      var d = obj.data; // 获取当前行的数据
      var layEvent = obj.event; // 获取事件名（edit 或 del）
      if (obj.tr) {
        obj.tr.on("click", function (e) {
          e.preventDefault(); // 防止默认行为
        });
      }
      if (layEvent == "del") {
        const index = $(obj.tr[0]).data("index");
        let list = table.cache["purchasePlanFormTable"].filter((v) => {
          return v["LAY_TABLE_INDEX"] != index;
        });
        table.reload("purchasePlanFormTable", {
          data: list
        });
      }
    });
    // $("#Configure").click(function () {
    //   if (table.cache["purchasePlanFormTable"].some((v) => v.workshopId == "" && v.productionLineId == "")) {
    //     layer.msg("请完善表格数据");
    //   } else {
    //     table.cache["purchasePlanFormTable"].push({
    //       workshopId: "",
    //       productionLineId: "",
    //       plannedProductionTime: "",
    //       plannedQuantity: "",
    //       remark: ""
    //     });
    //     tableVal.reload({
    //       data: table.cache["purchasePlanFormTable"]
    //     });
    //   }
    // });

    $("#processingDrawingBtn").click(function () {
      if ($("#processingDrawing").val()) {
        window.open($("#processingDrawing").val(), "_blank");
      } else {
        layer.msg("当前产品未配置图纸");
      }
    });
    $("#warehouseProductionOrderForm .layui-table-body").css("overflow", "scroll");
    $("#warehouseProductionOrderForm .layui-table-box").css("overflow", "visible");
    $("#warehouseProductionOrderForm .layui-table-view").css("overflow", "visible");
  });
</script>

<style>
  #warehouseProductionOrderForm .layui-form-label {
    width: 125px;
  }

  #warehouseProductionOrderForm .layui-input-block {
    margin-left: 155px;
  }

  #warehouseProductionOrderForm .layui-form-item .layui-inline {
    /* margin-bottom: 5px; */
    margin-right: 0px;
  }

  #warehouseProductionOrderForm .layui-table-cell {
    overflow: visible !important;
  }
</style>